package com.hzhr.iot.device.service;

import com.hzhr.iot.core.annotation.ApiImplicitInternalParams;
import com.hzhr.iot.core.exception.ServiceException;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrHttpUtil;
import com.hzhr.iot.core.util.HzhrJsonUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.constant.Device_ErrorsEnum;
import com.hzhr.iot.device.dao.CollectDeviceDao;
import com.hzhr.iot.device.dao.IotDeviceDao;
import com.hzhr.iot.device.dao.mapper.custom.PcRegulatorDeviceMonitorCollectDataMapper;
import com.hzhr.iot.device.entity.CollectDeviceEntity;
import com.hzhr.iot.device.entity.IotDeviceEntity;
import com.hzhr.iot.device.entity.RegulatorCollectDataEntity;
import com.hzhr.iot.device.model.regulatorDevice_monitor_collectData.RegulatorDevice_Monitor_CollectDataGetModel;
import com.hzhr.iot.device.model.regulatorDevice_monitor_collectData.RegulatorDevice_Monitor_CollectDataModel;
import com.hzhr.iot.device.model.regulatorDevice_monitor_commandSend.RegulatorDevice_Monitor_CommandSendGetModel;
import com.hzhr.iot.device.model.regulatorDevice_monitor_commandSend.RegulatorDevice_Monitor_CommandSendPostModel;
import com.hzhr.iot.device.queryModel.custom.CollectDeviceCustomQueryModel;
import com.hzhr.iot.device.queryModel.custom.IotDeviceCustomQueryModel;
import com.hzhr.iot.device.service.base.BaseService;
import com.hzhr.iot.user.sdk.model.user_password.User_PasswordGetModel;
import com.hzhr.iot.user.sdk.service.User_User_PasswordService;
import com.mysql.jdbc.log.LogFactory;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class RegulatorDevice_Monitor_CommandSendService extends BaseService {

    @Value("${xuntengPath}")
    private String xuntengPath;

    @Autowired
    CollectDeviceDao collectDeviceDao;
    @Autowired
    IotDeviceDao iotDeviceDao;

    private static Logger logger = LoggerFactory.getLogger(RegulatorDevice_Monitor_CommandSendService.class);

    //region javadoc注释 : post
    /**
     * 查询调压设备下的监控设备 <br/><br/>
     * 步骤 : <br/>
     * 1. 查询调压设备 : 查询调压设备，如果不存在则抛出异常“调压设备不存在” <br/>
     * 2. 查询监控设备：查询该调压设备下的监控设备，如果监控设备不存在，抛出异常“监控设备不存在” <br/>
     * 3. 验证监控设备是否具备发送目标指令的条件 ： <br/>
     *  (1) 如果指令类型为1(开阀)或2(开阀)，只有DTU才能够发送 <br/>
     *  如果监控设备不具备发送目标指令的条件，抛出异常“该监控设备无法进行此操作” <br/>
     * 4. 发送指令： <br/>
     *  (1) 如果指令类型为1(开阀)或2(开阀)，通过迅腾平台向设备推送指令。如果没有收到成功下发的响应，则抛出异常“指令下发异常”，并记录日志 <br/>
     * 5. 返回信息 <br/>
     * @param header <br/>
     * _token : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 令牌;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-user-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户编号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/>
     * _hzhr-user-code : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户代码;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-user-name : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户名;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-company-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 公司编号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/>
     * _hzhr-dept-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 部门编号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/>
     * _hzhr-user-type : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 用户类型(关联: common_service.options.code, typeCode = 'USER_TYPE');<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-transaction-id : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 交易流水号;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-transaction-type : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 交易类型;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : true;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : string;<br/>
     * _hzhr-access-mode : <br/>&nbsp&nbsp&nbsp&nbsp 说明 : 访问模式 0:一般 1:全局;<br/>&nbsp&nbsp&nbsp&nbsp 是否必填 : false;<br/>&nbsp&nbsp&nbsp&nbsp 默认值 : 0;<br/>&nbsp&nbsp&nbsp&nbsp 数据类型 : int;<br/><br/>
     * @param query <br/><br/>
     * @param regulatorDeviceId 调压设备编号 <br/><br/>
     * @param monitorId 监控设备编号 <br/><br/>
     * @param body <br/><br/>
     * @throws ServiceException <br/>
     * REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_201 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 查询调压设备<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 调压设备不存在<br/>
     * REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_202 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 查询监控设备<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 监控设备不存在<br/>
     * REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_203 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 验证监控设备是否具备发送目标指令的条件<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 该监控设备无法进行此操作<br/>
     * REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_204 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 发送指令<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 指令下发异常<br/>
     * @see RegulatorDevice_Monitor_CommandSendPostModel body <br/>
     * @see RegulatorDevice_Monitor_CommandSendGetModel result <br/>
     */ 
    //endregion
    //region 说明 : post
    //查询调压设备下的监控设备
    //步骤 :
    //1. 查询调压设备 : 查询调压设备，如果不存在则抛出异常“调压设备不存在”
    //2. 查询监控设备：查询该调压设备下的监控设备，如果监控设备不存在，抛出异常“监控设备不存在”
    //3. 验证监控设备是否具备发送目标指令的条件 ：
    // (1) 如果指令类型为1(开阀)或2(开阀)，只有DTU才能够发送
    // 如果监控设备不具备发送目标指令的条件，抛出异常“该监控设备无法进行此操作”
    //4. 发送指令：
    // (1) 如果指令类型为1(开阀)或2(开阀)，通过迅腾平台向设备推送指令。如果没有收到成功下发的响应，则抛出异常“指令下发异常”，并记录日志
    //5. 返回信息
    //endregion
    //region 参数 : post
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌",required = true, dataType = "string", paramType = "header"),

            @ApiImplicitParam(name = "regulatorDeviceId", value = "调压设备编号",required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "monitorId", value = "监控设备编号",required = true, dataType = "int", paramType = "path"),
    })
    @ApiImplicitInternalParams({
            @ApiImplicitParam(name = "_token", value = "令牌",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-id", value = "用户编号",required = true, dataType = "int", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-code", value = "用户代码",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-name", value = "用户名",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-company-id", value = "公司编号",required = true, dataType = "int", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-dept-id", value = "部门编号",required = true, dataType = "int", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-user-type", value = "用户类型(关联: common_service.options.code, typeCode = 'USER_TYPE')",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-transaction-id", value = "交易流水号",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-transaction-type", value = "交易类型",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "_hzhr-access-mode", value = "访问模式 0:一般 1:全局",defaultValue = "0", required = false, dataType = "int", paramType = "header"),
    })
    //endregion
    //region 请求 : post
    @RequestMapping(value = "/regulator-devices/{regulatorDeviceId}/monitors/{monitorId}/command-sends", method = RequestMethod.POST)
    //endregion
    public RegulatorDevice_Monitor_CommandSendGetModel post(Map<String, String> header, Integer regulatorDeviceId,
                                                           Integer monitorId, Map<String, Object> query,
                                                           RegulatorDevice_Monitor_CommandSendPostModel body) throws ServiceException {
        /* 查询调压设备 : 查询调压设备，如果不存在则抛出异常“调压设备不存在” */
        CollectDeviceCustomQueryModel collectDeviceCustomQueryModel = new CollectDeviceCustomQueryModel();
        collectDeviceCustomQueryModel.setEqual_id(regulatorDeviceId);
        collectDeviceCustomQueryModel.setEqual_isValid("1");
        int count = collectDeviceDao.selectCount(collectDeviceCustomQueryModel);
        if (count == 0) {
            throw new ServiceException(Device_ErrorsEnum.REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_201);
        }

        /* 查询监控设备：查询该调压设备下的监控设备，如果监控设备不存在，抛出异常“监控设备不存在” */
        IotDeviceCustomQueryModel iotDeviceCustomQueryModel = new IotDeviceCustomQueryModel();
        iotDeviceCustomQueryModel.setEqual_collectDeviceId(regulatorDeviceId);
        iotDeviceCustomQueryModel.setEqual_id(monitorId);
        iotDeviceCustomQueryModel.setEqual_isValid("1");
        iotDeviceCustomQueryModel.setShow(true);
        IotDeviceEntity monitor = iotDeviceDao.selectEntity(iotDeviceCustomQueryModel);
        if (monitor == null) {
            throw new ServiceException(Device_ErrorsEnum.REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_202);
        }

        /* 验证监控设备是否具备发送目标指令的条件 ：
            (1) 如果指令类型为1(开阀)或2(开阀)，只有DTU才能够发送
            如果监控设备不具备发送目标指令的条件，抛出异常“该监控设备无法进行此操作” */
        Integer type = body.getType();
        if (type == 1 || type == 2) {
            if (!"4".equals(monitor.getCategoryCode())) {
                throw new ServiceException(Device_ErrorsEnum.REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_203);
            }
        }

        /* 4. 发送指令：
            (1) 如果指令类型为1(开阀)或2(开阀)，通过迅腾平台向设备推送指令。如果没有收到成功下发的响应，则抛出异常“指令下发异常”，并记录日志 */
        Map response = null;
        try {
            RestTemplate restTemplate = new RestTemplate();
            MultiValueMap<String, Object> query1 = new LinkedMultiValueMap<>();
            query1.add("deviceCode", monitor.getCode());
            query1.add("post", "1");
            if (type == 1) {
                query1.add("onoff", "0");
            }
            if (type == 2) {
                query1.add("onoff", "1");
            }
            ResponseEntity<Map> result = restTemplate.postForEntity(xuntengPath, query1, Map.class);
            response = result.getBody();
        } catch (Throwable e) {
            logger.error("调用迅腾服务异常", e);
            throw new ServiceException(Device_ErrorsEnum.REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_204);
        }

        if (response == null || !"0".equals(HzhrTypeUtil.object2string(response.get("code")))) {
            if (response != null && !"0".equals(HzhrTypeUtil.object2string(response.get("code")))) {
                logger.error("调用迅腾平台下发指令错误：" + HzhrTypeUtil.object2string(response.get("msg")));
            }
            throw new ServiceException(Device_ErrorsEnum.REGULATORDEVICE_MONITOR_COMMANDSENDSERVICE_POST_204);
        }

        /* 返回信息 */
        RegulatorDevice_Monitor_CommandSendGetModel result = new RegulatorDevice_Monitor_CommandSendGetModel();
        return result;
    }
}

